package com.example.question.tree.tree3;

import com.example.question.tree.tree1.TreeNode;

/**
 * @Date 2023-07-14
 * @Author Jonathan
 */
public class Code09_235 {


    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        TreeNode ancestor = root;
        while (ancestor != null) {
            if (Math.max(p.val, q.val) < ancestor.val) {
                ancestor = ancestor.left;
            } else if (Math.min(p.val, q.val) > ancestor.val) {
                ancestor = ancestor.right;
            } else {
                break;
            }
        }
        return ancestor;
    }
}